<?php
use DengLuTong\DengLuTong;
include_once 'DengluTong/DengluTong.php';

class Application_Service_Login
{
	private static $_instance = NULL;
	
    private function __construct () {}
    
    private function __clone() {}
    
    public static function getInstance() {
    	if(self::$_instance == NULL) {
    		self::$_instance = new self();
    	}
    	return self::$_instance;
    }
    
    public function callback($platform, $act) {
    	$platform = empty( $platform ) ? '' : 'Vendor_' .$platform;
    	$dlt = DengLuTong::getInstance( $platform );
    	session_start();
    	$_SESSION['dlt'] = $dlt;
		if(!method_exists($dlt, $act)) {
		  throw new Exception('Method not exists.');
		}
		$return_user = $dlt->$act($platform);
		if(! $return_user)
			return false;
			
		$user_model = new Application_Model_User;
		$normal_user = $user_model->getUser($return_user['vendor'], $return_user['id']);
    	//return the exit
		if($normal_user) {
			return $normal_user;
		}
		//new user
		$normal_user = array();
		$normal_user['platform'] = $return_user['vendor'];
		$normal_user['platform_id'] = $return_user['id'];
		$normal_user['name'] = $return_user['name'];
		$normal_user['head'] = $return_user['img'];
		$normal_user['home_page'] = $return_user['url'];
		$normal_user['gender'] = $return_user['gender'];
		//$normal_user['home_page'] = 'http://weibo.com/'.$weibo_user['id'];
		$new_id = $user_model->insert($normal_user);
		$normal_user = $user_model->getUserById($new_id);
		if($normal_user)
			return $normal_user;
		return false;
    }
    
    public function logout() {
    	session_start();
    	$normal_user = $_SESSION['normal_user'];
    	if($_SESSION['normal_user']) {
	    	$dlt = DengLuTong::getInstance( $normal_user->platform );
	    	$dlt->logout();
	    	unset($_SESSION['normal_user']);
    	}
    }
}
?>